package unimelb.discussiontracker.twitter.service.integration;

import java.io.File;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class DirectoryMonitor {
    private String monitorFolder;

    private long pollingInterval;

    private FileAlterationListener listener;

    private FileAlterationMonitor monitor;

    public String getMonitorFolder() {
        return monitorFolder;
    }

    public void setMonitorFolder(String monitorFolder) {
        this.monitorFolder = monitorFolder;
    }

    public long getPollingInterval() {
        return pollingInterval;
    }

    public void setListener(FileAlterationListener listener) {
        this.listener = listener;
    }

    public void setPollingInterval(long pollingInterval) {
        this.pollingInterval = pollingInterval;
    }

    @PostConstruct
    public void start() {
        final File folderToMonitor = new File(monitorFolder);
        if (!folderToMonitor.exists()) {
            throw new IllegalArgumentException(monitorFolder + " does not exist");
        }
        if (!folderToMonitor.isDirectory()) {
            throw new IllegalArgumentException(monitorFolder + " is not a folder");
        }

        final FileAlterationObserver observer = new FileAlterationObserver(folderToMonitor);
        observer.addListener(listener);

        monitor = new FileAlterationMonitor(pollingInterval);
        monitor.addObserver(observer);
        try {
            monitor.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PreDestroy
    public void stop() {
        if (monitor != null) {
            try {
                monitor.stop();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
